package com.scy.controller2;

import com.scy.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/controller1")
public class Controller1 {

    public static List<RestHighLevelClient> list= new ArrayList();

    @RequestMapping("/initEsClient")
    @ResponseBody
    public User initESClient(
//            @RequestBody  // @RequestBody开启后必须用post方法
                    User user) {
        HttpHost httpHost = new HttpHost("localhost", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient esClient = new RestHighLevelClient( builder );
        System.out.println("客户端开启了");
        list.add(esClient);
        return new User("esClientSize", list.size()+"");
    }

    @RequestMapping("/closeEsClient")
    @ResponseBody
    public User closeESClient(
//            @RequestBody   // @RequestBody开启后必须用post方法
                    User user) {

        if (list.size()>0) {
            RestHighLevelClient restHighLevelClient = list.get(0);
            try {
                restHighLevelClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            list.remove(0);
        }

        return new User("esClientSize", list.size()+"");
    }
}
